package com.tarena.lbs.business.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.business.dao.mapper.BusinessMapper;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.StoreChainVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class BusinessRepositoryImpl implements BusinessRepository {
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public void save(BusinessPO po) {
        log.debug("保存商家信息业务，入参:{}", po);
        businessMapper.insert(po);
    }

    @Override
    public PageInfo<BusinessPO> pagesList(BusinessQuery query) {
        QueryWrapper<BusinessPO> queryWrapper = assembleBusinessQuery(query);
        //PageHelper.startPage 之间不能有代码
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<BusinessPO> pos = businessMapper.selectList(queryWrapper);
        //selectList 数据库操作 之间不能有代码
        return new PageInfo<>(pos);
    }

    @Override
    public List<StoreChainVO> getAll() {
        return  businessMapper.getAll();
    }

    @Override
    public int updateStatus(Integer id) {
        return businessMapper.updateStatus();
    }

    private QueryWrapper<BusinessPO> assembleBusinessQuery(BusinessQuery query) {
        QueryWrapper<BusinessPO> queryWrapper = new QueryWrapper<>();
        //1.business_name 商家名称 模糊查询 非空 where business_name like(%#{}%)
        if (StringUtils.isNotBlank(query.getBusinessName())){
            queryWrapper.like("business_name",query.getBusinessName());
        }
        //2.business_head_phone 负责人电话 模糊查询 非空 where business_head_phone like(%#{}%)
        if (StringUtils.isNotBlank(query.getBusinessHeadPhone())){
            queryWrapper.like("business_head_phone",query.getBusinessHeadPhone());
        }
        //3. business_status 状态 条件查询 非空 where business_status = #{businessStatus}
        if (query.getBusinessStatus() != null){
            queryWrapper.eq("business_status",query.getBusinessStatus());
        }
        //4. entry_time 创建时间 模糊查询 非空 where entry_time between #{startingTime} and #{endTime}
        if (query.getStartingTime() != null && query.getEndTime() != null){
            queryWrapper.between("entry_time",query.getStartingTime(),query.getEndTime());
        }
        return queryWrapper;
    }
}
